<template>
  <div>
    <!-- type="border-card" -->
    <el-col :span="24">
      <el-tabs ref="tabs" v-model="tab" v-loading="loading" class="custom-tabs" @tab-click="handleClick">
        <el-tab-pane :label="$t('资产负债表')" name="balance_sheet">
          <diff
            ref="balanceSheet"
            :sheet-data="uploadData.balanceSheet"
            :disabled="disabled"
            :company-id="companyId"
            type="balance_sheet"
            @receve="deleteHandler"
          />
        </el-tab-pane>
        <el-tab-pane :label="$t('利润表')" name="income_sheet">
          <diff
            ref="incomeSheet"
            :sheet-data="uploadData.incomeSheet"
            :disabled="disabled"
            :company-id="companyId"
            type="income_sheet"
            @receve="deleteHandler"
          />
        </el-tab-pane>
        <el-tab-pane :label="$t('现金流量表')" name="cash_flow_sheet">
          <diff
            ref="cashFlowSheet"
            :sheet-data="uploadData.cashFlowSheet"
            :disabled="disabled"
            :company-id="companyId"
            type="cash_flow_sheet"
            @receve="deleteHandler"
          />
        </el-tab-pane>
        <el-tab-pane :label="$t('关键指标')" name="data_key">
          <div>
            <!--关键指标信息-->
            <div class="area-header">
              <span class="area-header-title">
                {{ $t('关键指标') }}
                <el-tooltip placement="top">
                  <div slot="content">
                    <span v-html="$t('1. 点击“新增”可创建新的关键指标；<br>')" />
                    <span v-html="$t('2. 点击“选择公式”，可编辑修改指标公式；<br>')" />
                    <span v-html="$t('3. 含公式的指标值系统将自动计算，不可修改；<br>')" />
                    <span v-html="$t('4. 不含公式的指标值，用户需手动维护指标值；<br>')" />
                    <span v-html="$t('5. 公司首次创建财务数据时，默认从系统设置中同步关键指标。<br>')" />
                  </div>
                  <i class="el-icon-question" />
                </el-tooltip>
              </span>
            </div>
            <el-table
              :data="uploadData.dataKeys"
              row-key="id"
              default-expand-all
              height="80vh"
              border
            >
              <el-table-column :label="$t('分类')" width="160" align="left" prop="keyReport" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-if="scope.row.pid === '0'">{{ $t(scope.row.keyReport) }}</span>
                  <el-input v-if="!scope.row.id" v-model="scope.row.keyReport" :placeholder="$t('分类')" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('指标名称')" width="250" align="center" prop="keyName" show-overflow-tooltip>
                <template slot-scope="scope">
                  <el-input v-if="scope.row.pid !== '0'" ref="keyName" v-model="scope.row.keyName" disabled :placeholder="$t('指标名称')" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('公式')" align="right" prop="indicatorsFormula">
                <template slot-scope="scope">
                  <div class="overflowText">
                    <span v-if="scope.row.pid !== '0'" :title="formatGS(scope.row)" v-text="formatGS(scope.row)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column :label="$t('值')" width="100" align="center" prop="keyValue">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.pid !== '0'" v-model="scope.row.keyValue" oninput="value=value.replace(/[^\d.]/g,'')" disabled :readonly="scope.row.indicatorsFormula && scope.row.indicatorsFormula !== ''" />
                </template>
              </el-table-column>
              <el-table-column :label="$t('排序')" width="100" align="center" prop="sort">
                <template slot-scope="scope">
                  <el-input v-if="scope.row.pid !== '0'" v-model="scope.row.sort" disabled oninput="value=value.replace(/[^\d.]/g,'')" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="$t('科目校验')" name="subject_validation">
          <pcw-subject-validation-list ref="pcwSubjectValidationList" height="80vh" :table-data="uploadData.validationList" @subjectValidation="validationHandle" />
        </el-tab-pane>
        <el-tab-pane :label="$t('附件上传')" name="fileList">
          <el-form label-width="120px" class="dataForm">
            <FileTable :list.sync="uploadData.fileList" data-type="pcw_data_main" :business-id="companyId" />
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <div v-show="hideTab" class="item_tab_center" style="display: flex; align-items: center;">
      <span class="tab_item link-type">科目信息</span>
      <span class="tab_item" @click="balanceSubjectHandler">平衡科目 <i class="badge">{{ warningCount }}</i></span>
      <span class="tab_item_unit" style="">金额单位</span>
      <dictSelect
        v-model="uploadData.unit"
        size="mini"
        :clearable="false"
        style="width: 100px;"
        dictionary="finance_unit"
        @change="multChange"
      />
    </div>
    <div class="tabs_buttons">
      <!-- <el-form-item :label="$t('单位')" prop="unit">
          <dictSelect
            v-model="form.unit"
            size="small"
            :clearable="true"
            dictionary="finance_unit"
          />
        </el-form-item> -->
      <el-button size="mini" @click="cancel">{{ $t('取消') }}</el-button>
      <el-button v-show="delHide" size="mini" type="danger" @click="deleteSubject">{{ $t('删除') }}</el-button>
      <!-- <el-button v-if="!view" size="mini" type="success" @click="updateTemplate">{{ $t('更新模板') }}</el-button> -->
      <el-button v-show="!view" type="primary" size="mini" @click="updateSheetData">{{ $t('确定') }}</el-button>
      <!-- <el-button v-if="!disabled" size="mini" type="success" @click="updateTemplate">{{ $t('更新模板') }}</el-button> -->
      <el-button v-show="view && tab === 'subject_validation'" type="warning" size="mini" @click="validationHandle">{{ $t('校验') }}</el-button>
      <el-button v-show="view" type="primary" size="mini" @click="save">{{ $t('确定') }}</el-button>

    </div>
    <el-dialog
      title="提示"
      :visible.sync="finalTipOpen"
      :lock-scroll="false"
      append-to-body
      width="30%"
    >
      <div>
        <el-table
          :data="passArrayData"
          style="width: 100%"
          max-height="500"
          border
          :show-header="passArrayData.length>0"
        >
          <template slot="empty">
            <el-empty description="科目校验全部通过" />
          </template>
          <el-table-column
            prop="name"
            label="以下校验未通过"
          >
            <template slot-scope="scope">
              <el-link type="danger" :underline="false">{{ scope.row.name }}</el-link>
            </template>
          </el-table-column>

        </el-table>
      </div>
      <!-- <el-form class="demo-form-inline"> -->
      <!-- <el-form-item label="">
          <el-radio v-model="finalTipOpenRaion" label="1">查看校验</el-radio>
          <el-radio v-model="finalTipOpenRaion" label="2">强制保存</el-radio>
        </el-form-item> -->
      <!-- </el-form> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="finalTipClick('1')">查看校验</el-button>
        <el-button type="primary" :disabled="!finalTipOpen" @click="finalTipClick('2')">继续保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Diff from '@/views/company/pcw/diff'
import PcwSubjectValidationList from '@/views/company/pcw/pcwSubjectValidationList'
import { subjectValidation, getTempKeyByCompanyId, getTempValidationByCompanyId, updateTemp } from '@/api/company/pcw/pcwDataMain'

export default {
  name: 'PcwDataMainTab',
  components: { PcwSubjectValidationList, Diff },
  props: {
    uploadData: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    },
    companyId: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      tab: 'balance_sheet',
      loading: false,
      // 是否更新模板
      updateTemp: false,
      // 点击按钮查看时隐藏 校验和确定按钮
      view: true,
      finalTipOpen: false, // 保存的弹出层
      finalTipOpenRaion: '1',
      passArrayData: [],
      delHide: false,
      sheetType: '',
      warningCount: 0,
      hideTab: true
    }
  },
  methods: {
    cancel() {
      this.$emit('cancel')
    },
    save() {
       // 1. 先触发校验
      this.validationHandle().then((res) => {
          this.finalTipOpen = true
          this.finalTipOpenRaion = '1'
          const passArray = res.filter(item => { return !item.pass })
          this.passArrayData = passArray
      })
    },
    finalTipClick(tip) {
        if (tip === '1') {
           this.tab = 'subject_validation'
           this.finalTipOpen = false
        } else {
              console.log('开始保存')
              if (this.updateTemp) {
              this.loading = true
              updateTemp(this.uploadData).then(res => {
                this.loading = false
                if (res.code === 200) {
                  this.msgSuccess(this.$t('保存成功'))
                  this.finalTipOpen = false
                  this.$emit('save')
                }
              })
            } else {
              this.finalTipOpen = false
              this.$emit('save')
            }
        }
    },
    updateSheetData() {
      const loading = this.$loading()
        updateTemp(this.uploadData).then(res => {
          if (res.code === 200) {
            this.msgSuccess(this.$t('保存成功'))
            loading.close()
            this.$parent.$parent.tabOpen = false
            this.$parent.$parent.getList()
          }
        })
    },
    init() {
      this.updateTemp = false
      this.componentInit()
    },
    componentInit() {
      this.tab = 'balance_sheet'
      this.$nextTick(() => {
        this.$refs.balanceSheet.init()
        this.$refs.incomeSheet.init()
        this.$refs.cashFlowSheet.init()
        setTimeout(this.handleClick, 800)
      })
    },
    formatGS(row) {
      if (row.indicatorsFormula === '' || row.indicatorsFormula === null) {
        return ''
      }
      return this.$t(row.indicatorsFormula)
    },
    validationHandle() {
      return new Promise((resolve) => {
        this.$refs.pcwSubjectValidationList.loading = true
          const sheetData = Object.assign({}, this.uploadData)
          subjectValidation({
            companyId: this.companyId,
            sheetData
          }).then(res => {
            this.uploadData.validationList = res.data
            resolve(res.data)
            this.$refs.pcwSubjectValidationList.loading = false
          }).catch(() => {
            this.$refs.pcwSubjectValidationList.loading = false
          })
      })
    },
    updateTemplate() {
      this.updateTemp = true
      this.loading = true
      Promise.all([
        getTempKeyByCompanyId(this.companyId).then(res => {
          this.uploadData.dataKeys = res.data
        }),
        getTempValidationByCompanyId(this.companyId).then(res => {
          this.uploadData.validationList = res.data
        })
      ]).then(() => {
        this.loading = false
      })
    },
    deleteHandler(data, type) {
      if (data && data.length > 0) {
          this.delHide = true
      } else {
          this.delHide = false
      }
      this.sheetType = type
    },
    deleteSubject() {
      // 删除科目

      if (this.sheetType === 'balance_sheet') {
          this.$refs['balanceSheet'].multipleDelHandle()
      } else if (this.sheetType === 'income_sheet') {
          this.$refs['incomeSheet'].multipleDelHandle()
      } else if (this.sheetType === 'cash_flow_sheet') {
          this.$refs['cashFlowSheet'].multipleDelHandle()
      }
    },
    balanceSubjectHandler() {
      // this.subjectDrawer = true
      if (this.tab === 'balance_sheet') {
        this.$refs['balanceSheet'].initBalanceTableData(true)
      } else if (this.tab === 'income_sheet') {
        this.$refs['incomeSheet'].initBalanceTableData(true)
      } else if (this.tab === 'cash_flow_sheet') {
        this.$refs['cashFlowSheet'].initBalanceTableData(true)
      }
    },
    handleClick() {
      const tabToRefMap = {
          'balance_sheet': 'balanceSheet',
          'income_sheet': 'incomeSheet',
          'cash_flow_sheet': 'cashFlowSheet'
      }
      if (this.tab in tabToRefMap) {
          this.hideTab = true
          const refName = tabToRefMap[this.tab]
          const arr = this.$refs[refName].initBalanceTableData(false)
          const warningArr = arr.filter(item => item.status === 'warning')
          this.warningCount = warningArr.length
      } else {
          this.hideTab = false
      }
    },
    multChange(val) {
      console.log(val)
    }
  }
}
</script>

<style scoped lang="scss">
.tabs_buttons {
  position: absolute;
  bottom: 20px;
  right: 20px;
}
.item_tab_center{
  position: absolute;
  left: 50%;
  transform: translate(0%, 5%);
}
.tab_item{
    padding: 0 20px;
    height: 40px;
    box-sizing: border-box;
    display: inline-block;
    list-style: none;
    line-height: 36px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    position: relative;
    cursor: pointer;
}
.tab_item_unit{
    padding: 0 20px;
    height: 40px;
    box-sizing: border-box;
    display: inline-block;
    list-style: none;
    line-height: 36px;
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    position: relative;
}
// .item {
//   top: 8px;
//   right: 24px;
// }
/deep/.el-badge__content.is-fixed{
  top: 8px;
  right: 24px;
}
.badge{
  position: absolute;
  top: 8px;
  right: 30px;
  transform: translateY(-50%) translateX(100%);
  border-radius: 10px;
  color: #fff;
  display: inline-block;
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  text-align: center;
  white-space: nowrap;
  background-color: #E6A23C;
  font-style: normal;
}
</style>
